package com.android.lovely.ui.fragment

import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.filter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.android.lovely.R
import com.android.lovely.const.ChatChange
import com.android.lovely.data.CardItem
import com.android.lovely.data.MyCardBean
import com.android.lovely.databinding.FragmentBaseListBinding
import com.android.lovely.databinding.ItemMyCardBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseLoadAdapter
import com.android.lovely.framework.BaseLoadFragment
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.UIController.dismissLoading
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.ui.activity.BigCardActivity
import com.android.lovely.ui.activity.HomeActivity
import com.android.lovely.ui.activity.OptimizationActivity
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.fragment.MyCardAdapter.OnItemClickListener
import com.android.lovely.ui.viewmodel.MyCardViewModel
import com.kotlin.extensions.appContext
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine

/**
 *
 * @author why
 * @date 2025/3/24 18:53
 */
class MyCardsFragment:
    BaseLoadFragment<FragmentBaseListBinding, MyCardBean>() {

    private val mViewModel by activityViewModels<MyCardViewModel>()
    override fun getViewModel(): BaseLoadViewModel<MyCardBean> {
        return mViewModel
    }

    override fun initView() {
        getStateLayout().update()
        getRecyclerView().addItemDecoration(HomeListItemDecoration(10.dp))
        super.initView()
        lifecycleScope.launchSafety {
            FlowBus.flowOf<ChatChange>().collectLatest {
                mBinding.srlRefresh.isRefreshing = true
                adapter.refresh()
            }
        }
    }

    override fun setNoContent() {
        getStateLayout().setNoContentIcon(R.drawable.icon_no_search)
        getStateLayout().setNoContentText(getString(R.string.no_my_card))
        getStateLayout().setNoContentButton(getString(R.string.refresh_no_my_card), true) {
            startPage<HomeActivity>("position" to 1)
        }
    }

    override fun getStateLayout(): FlexibleContentContainer {
        return mBinding.flexState
    }

    override fun getSwipeRefreshLayout(): SwipeRefreshLayout {
        return mBinding.srlRefresh
    }

    override fun getRecyclerView(): RecyclerView {
        return mBinding.rv
    }

    override fun getBaseAdapter(): BaseLoadAdapter<MyCardBean, *> {
        val adapter = MyCardAdapter(mViewModel)
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemOpen(item: MyCardBean, position: Int) {
                val cards = adapter.snapshot().mapNotNull {
                    it?.let { it1 ->
                        CardItem(
                            id = it1.cardId,
                            cardUrl = it.cardUrl,
                            intimacyValue = 0,
                            point = 0,
                            isUnlock = true
                        )
                    }
                }.toMutableList()

                BigCardActivity.start(
                    requireActivity(),
                    item.botId,
                    position,
                    item.botInfo?.name ?: "",
                    cards
                )
            }

            override fun onItemDelete(item: MyCardBean, position: Int) {
                requireActivity().showLovelyDialog{
                    setDialogTitle(getString(R.string.notice))
                    setDialogMessage(getString(R.string.delete_card))
                    setPositiveButton {
                        lifecycleScope.launchSafety {
                            mViewModel.delete(item.cardId)
                        }.onError {
                            dismissLoading()
                        }
                    }
                }
            }
        })
        return adapter
    }

    override suspend fun initData() {
        mViewModel.pager.combine(mViewModel.removedFlow) { data, remove ->
            data.filter { it.cardId !in remove }
        }.collectLatest {
            adapter.submitData(it)
        }
    }
}

class MyCardAdapter(val viewModel: MyCardViewModel) :
    BaseLoadAdapter<MyCardBean, MyCardHolder>(
        object :
            DiffUtil.ItemCallback<MyCardBean>() {
            override fun areItemsTheSame(
                oldItem: MyCardBean,
                newItem: MyCardBean
            ): Boolean {
                return oldItem.cardId == newItem.cardId
            }

            override fun areContentsTheSame(
                oldItem: MyCardBean,
                newItem: MyCardBean
            ): Boolean {
                return oldItem == newItem
            }

        }
    ) {

    private var listener: OnItemClickListener? = null
    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.listener = listener
    }

    override fun onBindViewHolder(holder: MyCardHolder, position: Int) {
        val item = getItem(position) ?: return
        holder.binding.apply {
//            root.clickable { onItemClickListener?.invoke(item, position) }
            ivImage.loadWithPlaceholder(item.cardUrl)
            ivImage.clickable {
                listener?.onItemOpen(item, position)
            }
            ivDelete.clickable {
                listener?.onItemDelete(item, position)
            }
            report.clickable { appContext.startPage<OptimizationActivity>("user_id" to item.botId) }
        }
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyCardHolder {
       return MyCardHolder(p0)
    }

    interface OnItemClickListener {
        fun onItemOpen(item: MyCardBean, position: Int)
        fun onItemDelete(item: MyCardBean, position: Int)
    }

}

class MyCardHolder(
    parent: ViewGroup,
    val binding: ItemMyCardBinding = ItemMyCardBinding.inflate(
        parent.layoutInflater,
        parent,
        false
    )
) : RecyclerView.ViewHolder(binding.root)